import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { videoAPI } from '../services/api';
import { Video } from '../types';
import Avatar from '../components/Avatar';

const Home: React.FC = () => {
  const navigate = useNavigate();
  const [videos, setVideos] = useState<Video[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState('发现');

  // 虚拟数据
  const mockVideos: Video[] = [
    {
      id: 1,
      title: "带三位女室友开公司",
      description: "创业路上的有趣故事",
      videoUrl: "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
      thumbnail: "https://picsum.photos/300/400?random=1",
      username: "一次就好718",
      userId: 1,
      views: 12722,
      likes: 231,
      createdAt: "2024-01-15T10:30:00Z",
      isLiked: false
    },
    {
      id: 2,
      title: "军事训练日常",
      description: "军旅生活的点点滴滴",
      videoUrl: "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
      thumbnail: "https://picsum.photos/300/400?random=2",
      username: "霾癆影视",
      userId: 2,
      views: 8963,
      likes: 4666,
      createdAt: "2024-01-15T11:30:00Z",
      isLiked: false
    },
    {
      id: 3,
      title: "被一只猫整无语了",
      description: "可爱猫咪的日常",
      videoUrl: "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
      thumbnail: "https://picsum.photos/300/400?random=3",
      username: "猫咪达人",
      userId: 3,
      views: 15670,
      likes: 506,
      createdAt: "2024-01-15T12:30:00Z",
      isLiked: false
    },
    {
      id: 4,
      title: "今天又喜收万家岭爱徒一名",
      description: "传统技艺的传承",
      videoUrl: "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
      thumbnail: "https://picsum.photos/300/400?random=4",
      username: "唢呐吴振",
      userId: 4,
      views: 7252,
      likes: 239,
      createdAt: "2024-01-15T13:30:00Z",
      isLiked: false
    }
  ];

  const fetchVideos = async () => {
    try {
      setLoading(true);
      const videoList = await videoAPI.getVideos();
      if (videoList && videoList.length > 0) {
        setVideos(videoList);
      } else {
        if (process.env.NODE_ENV === 'development') {
          console.log('使用虚拟数据');
        }
        setVideos(mockVideos);
      }
    } catch (error: any) {
      if (process.env.NODE_ENV === 'development') {
        console.log('API调用失败，使用虚拟数据:', error.message);
      }
      setVideos(mockVideos);
      setError(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchVideos();
  }, []);

  const handleLike = async (video: Video) => {
    // 简单的点赞逻辑
    setVideos(prev => prev.map(v => 
      v.id === video.id ? { ...v, isLiked: !v.isLiked, likes: v.isLiked ? v.likes - 1 : v.likes + 1 } : v
    ));
  };

  const handleFollow = async (video: Video) => {
    // 简单的关注逻辑
    alert('关注成功');
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-red-500 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (error && videos.length === 0) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-500 mb-4">{error}</p>
          <button 
            onClick={fetchVideos}
            className="bg-red-500 text-white px-4 py-2 rounded"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-white">
      {/* 顶部状态栏 */}
      <div className="bg-white px-4 py-2 flex items-center justify-between text-sm">
        <div className="flex items-center space-x-2">
          <span className="text-gray-600">14:59</span>
          <div className="w-4 h-2 bg-blue-500 rounded"></div>
        </div>
        <div className="flex items-center space-x-2">
          <span className="text-red-500 font-bold text-lg">快手</span>
        </div>
        <div className="flex items-center space-x-2">
          <div className="w-1 h-1 bg-gray-400 rounded-full"></div>
          <div className="w-1 h-1 bg-gray-400 rounded-full"></div>
          <div className="w-1 h-1 bg-gray-400 rounded-full"></div>
          <div className="w-4 h-2 bg-blue-500 rounded"></div>
          <span className="text-xs">53</span>
        </div>
      </div>

      {/* 顶部导航栏 */}
      <div className="bg-white px-4 py-3 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-6">
            <button className="text-sm text-gray-600">暑期心愿</button>
            <button className="text-sm text-gray-600">商城</button>
            <button className="text-sm text-gray-600">关注</button>
            <button className="text-sm text-red-500 font-medium border-b-2 border-red-500 pb-1">发现</button>
            <button className="text-sm text-gray-600">同城</button>
          </div>
          <button className="text-gray-600">
            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
              <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
            </svg>
          </button>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="flex-1 p-4 pb-20">
        {videos.length > 0 ? (
          <div className="grid grid-cols-2 gap-4">
            {videos.map((video) => (
              <div key={video.id} className="bg-white rounded-lg overflow-hidden shadow-sm">
                {/* 视频缩略图 */}
                <div className="relative aspect-[3/4] bg-gray-200">
                  <img 
                    src={video.thumbnail} 
                    alt={video.title}
                    className="w-full h-full object-cover cursor-pointer"
                    onClick={() => navigate(`/video/${video.id}`)}
                  />
                  
                  {/* 观看次数覆盖 */}
                  <div className="absolute top-2 left-2 bg-yellow-500 text-black text-xs px-2 py-1 rounded">
                    {video.views}次观看
                  </div>
                  
                  {/* 视频时长/信息覆盖 */}
                  <div className="absolute bottom-2 right-2 bg-gray-800 bg-opacity-70 text-white text-xs px-2 py-1 rounded">
                    {video.likes}
                  </div>
                </div>

                {/* 视频信息 */}
                <div className="p-3">
                  {/* 用户信息 */}
                  <div className="flex items-center space-x-2 mb-2">
                    <div className="w-6 h-6 bg-gray-300 rounded-full flex items-center justify-center">
                      <span className="text-white text-xs font-medium">a</span>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm text-gray-900 truncate cursor-pointer" onClick={() => navigate(`/video/${video.id}`)}>{video.title}</p>
                      <p className="text-xs text-gray-500">@{video.username}</p>
                    </div>
                  </div>

                  {/* 交互按钮 */}
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <button
                        onClick={() => handleLike(video)}
                        className="flex items-center space-x-1 text-xs text-gray-600 hover:text-red-500 transition-colors duration-200 cursor-pointer"
                      >
                        <span>{video.isLiked ? '❤️' : '🤍'}</span>
                        <span>{video.likes}</span>
                      </button>
                      <button
                        onClick={() => navigate(`/video/${video.id}`)}
                        className="flex items-center space-x-1 text-xs text-gray-600 hover:text-blue-500 transition-colors duration-200 cursor-pointer"
                      >
                        <span>💬</span>
                        <span>评论</span>
                      </button>
                    </div>
                    <button
                      onClick={() => handleFollow(video)}
                      className="text-xs text-red-500 hover:text-red-600 transition-colors duration-200 cursor-pointer"
                    >
                      关注
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8">
            <p className="text-gray-500 mb-4">暂无视频</p>
            <button 
              onClick={() => navigate('/upload')}
              className="bg-red-500 text-white px-4 py-2 rounded cursor-pointer"
            >
              发布视频
            </button>
          </div>
        )}
      </div>

      {/* 底部导航栏 */}
      <div className="fixed bottom-0 left-0 right-0 bg-black z-50">
        <div className="flex items-center justify-around py-3">
          <button className="flex flex-col items-center space-y-1 text-red-500 cursor-pointer">
            <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 24 24">
              <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
            </svg>
            <span className="text-xs">首页</span>
          </button>
          <button className="flex flex-col items-center space-y-1 text-gray-400 hover:text-red-500 transition-colors duration-200 cursor-pointer">
            <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 24 24">
              <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
            </svg>
            <span className="text-xs">关注</span>
          </button>
          <button className="flex flex-col items-center space-y-1 text-gray-400 hover:text-red-500 transition-colors duration-200 cursor-pointer">
            <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 24 24">
              <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
            </svg>
            <span className="text-xs">消息</span>
          </button>
          <button className="flex flex-col items-center space-y-1 text-gray-400 hover:text-red-500 transition-colors duration-200 relative cursor-pointer">
            <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 24 24">
              <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
            </svg>
            <span className="text-xs">我的</span>
            <div className="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"></div>
          </button>
        </div>
      </div>
    </div>
  );
};

export default Home; 